package dyyx;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class TraceIdUtils {
	
	private static final Random rand = new Random();
	
	private static final int MIN = 100000;
	private static final int MAX = 900000;

	private static final AtomicInteger seq = new AtomicInteger(MIN);
	
	
	


    private static final ThreadLocal<String> traceIdCache
            = new ThreadLocal<String>();

    public static String getTraceId() {
        return traceIdCache.get();
    }

    public static void setTraceId(String traceId) {
    	
    	
        traceIdCache.set(traceId);
    }

    public static void clear() {
        traceIdCache.remove();
    }
    
    public static String genTraceId() {
    	StringBuilder sb = new StringBuilder(64);
    	sb.append(LocalDateTime.now().toString());
    	sb.append("_");
    	sb.append(getSeq());
    	sb.append("_");

    	sb.append(rand.nextInt(10000));

    	return  sb.toString();
    }
    
    public static final int getSeq() {
    	int seqtmp = seq.getAndIncrement();
    	if(seqtmp>MAX) {
    		seqtmp = MAX;
    		seq.set(MIN);
    	}
    	return seqtmp;
    }
    
    
}